package LeedCode_BinaryTree;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:通过前序遍历和中序遍历创建二叉树
 * User: 阿宾
 * Date: 2024-11-27
 * Time: 09:31
 */
public class Demo9 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }
    //方法2
    public int preIndex;
    private int findIndex(int[] inorder,int inbegin,int inend,int key){
        for (int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
    private TreeNode buildTreeBuild(int[] preorder, int[] inorder,int inbegin,int inend){

        if(inbegin > inend){
            return null;
        }
        //根据前序指针创建根节点
        TreeNode root = new TreeNode(preorder[preIndex]);
        int inIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
        if(inIndex == -1){
            return null;
        }
        preIndex++;
        root.left = buildTreeBuild(preorder,inorder,inbegin,inIndex-1);
        root.right = buildTreeBuild(preorder,inorder,inIndex+1,inend);

        return root;
    }
    //方法2
    public TreeNode buildTree1(int[] preorder, int[] inorder) {

        return buildTreeBuild(preorder,inorder,0,inorder.length-1);

    }


    //方法1----------------------------------------------------------
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0){
            return null;
        }
        //找到根节点在中序遍历位置
        int index = -1;
        TreeNode root = new TreeNode(preorder[0]);

        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == preorder[0]){
                index = i;
                break;
            }
        }
        //分割中序遍历
        int[] Leftinorder = Arrays.copyOfRange(inorder,0,index);
        int[] Rightinorder = Arrays.copyOfRange(inorder,index+1,inorder.length);

        //分割前序遍历
        int[] Leftpreorder = Arrays.copyOfRange(preorder,1,1+Leftinorder.length);
        int[] Rightpreorder = Arrays.copyOfRange(preorder,1+Leftinorder.length,preorder.length);

        root.left = buildTree(Leftpreorder,Leftinorder);
        root.right = buildTree(Rightpreorder,Rightinorder);

        return root;

    }
    public static void main(String[] args) {

    }
}
